import React, { Component } from 'react';
import wangEditor from 'wangeditor'
import { Link } from 'react-router-dom'

import './editor.css'
import { Button } from 'antd';

/**
 * 文章编辑器
 * @param title 标题
 * @param content 内容
 * @param onSave(title, content) 保存触发
 * @param onPublish 发布触发
 */
class Editor extends Component {

    state = {
        editor: null,
        title: '',
    }

    componentDidMount() {
        var editor = new wangEditor('#editor')
        // 下面两个配置，使用其中一个即可显示“上传图片”的tab。但是两者不要同时使用！！！
        editor.customConfig.uploadImgShowBase64 = true   // 使用 base64 保存图片
        editor.customConfig.uploadImgServer = '/upload'  // 上传图片到服务器

        editor.create()
        //设置内容和标题
        const { title, content } = this.props
        editor.txt.html(content)
        this.setState({ editor, title })

        //设置热键
        let hotkey = ""
        document.onkeydown = (e) => {
            if (e.keyCode != hotkey.substr(0, 2)) {
                hotkey = e.keyCode + hotkey
            }
            hotkey = hotkey.substr(0, 4)
            if (hotkey == "8317") {
                this.saveHandler()
                e.preventDefault();
            }
        }
    }

    componentWillUnmount() {
        document.onkeydown = null
    }

    //编辑标题
    titleHandler = (title) => {
        this.setState({ title })
    }

    //保存文章
    saveHandler = () => {
        const editor = this.state.editor
        const content = editor.txt.html()
        this.props.onSave && this.props.onSave(this.state.title, content)
    }

    //发布文章
    publishHandler = () => {
        this.props.onPublish && this.props.onPublish()
    }

    render() {
        return (
            <div className="editorbox">
                <div>
                    <input className="title" value={this.state.title} onChange={(e) => this.titleHandler(e.target.value)} />
                </div>
                <ul className="mymenu">
                    <li onClick={this.saveHandler}><i className="iconfont icon-baocun" /></li>
                    <li onClick={this.publishHandler}><i className="iconfont icon-gengxin" />已发布</li>
                </ul>

                {/* 编辑器插件 */}
                <div id="editor"></div>

            </div>
        );
    }
}

export default Editor